import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../styles" as Styles

/**
 * CreateTaskDialog - 新建任务对话框
 * 基于CustomDialog的无边框设计
 */
CustomDialog {
    id: createTaskDialog

    // 从外部注入
    property var availableTemplates: []
    property var taskViewModel: null
    property var availableAgvs: []

    // 派生数据
    property var agvOptions: []

    // 内部数据
    property string selectedTemplate: ""
    property var selectedAgvId: ""  // 空字符串表示自动选择

    // 配置对话框
    title: qsTr("新建任务")
    dialogWidth: 520
    dialogHeight: 500
    okButtonText: qsTr("创建任务")
    okButtonEnabled: selectedTemplate !== ""

    // 重写信号
    onAccepted: {
        var taskData = {
            templateName: selectedTemplate,
            agvId: selectedAgvId  // 空字符串表示自动选择
        }
        taskAccepted(taskData)
    }

    // 自定义信号
    signal taskAccepted(var taskData)
    signal taskRejected()

    // 内容区域
    contentItem: ColumnLayout {
        width: parent.width
        spacing: Styles.Theme.spacingLarge

        // 任务配置区域
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: configColumn.height + Styles.Theme.spacingLarge * 2
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusNormal

            ColumnLayout {
                id: configColumn
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: Styles.Theme.spacingLarge
                spacing: Styles.Theme.spacingNormal

                // 区域标题
                Text {
                    text: qsTr("任务配置")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeMedium
                    font.weight: Styles.Theme.fontWeightMedium
                }

                // 任务模板选择
                ColumnLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        text: qsTr("任务模板")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }

                    CustomComboBox {
                        id: templateCombo
                        Layout.fillWidth: true
                        Layout.preferredHeight: 48
                        model: availableTemplates
                        currentIndex: -1
                        placeholderText: qsTr("请选择模板...")

                        onActivated: function(index) {
                            selectedTemplate = currentText
                        }
                    }
                }

                // AGV选择
                ColumnLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        text: qsTr("执行AGV")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                    }

                    CustomComboBox {
                        id: agvCombo
                        Layout.fillWidth: true
                        Layout.preferredHeight: 48
                        model: createTaskDialog.agvOptions
                        currentIndex: 0
                        textRole: "text"
                        valueRole: "value"

                        onActivated: function(index) {
                            selectedAgvId = (currentValue === undefined || currentValue === null) ? "" : currentValue
                        }
                    }

                    // 提示信息
                    Text {
                        text: "💡 " + qsTr("选择'自动选择'将由系统分配最合适的AGV")
                        color: Styles.Theme.textTertiary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        wrapMode: Text.WordWrap
                        Layout.fillWidth: true
                    }
                }
            }
        }

        // 任务预览区域
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: previewColumn.height + Styles.Theme.spacingLarge * 2
            color: Styles.Theme.background
            border.color: Styles.Theme.divider
            border.width: 1
            radius: Styles.Theme.radiusNormal

            ColumnLayout {
                id: previewColumn
                anchors.left: parent.left
                anchors.right: parent.right
                anchors.top: parent.top
                anchors.margins: Styles.Theme.spacingLarge
                spacing: Styles.Theme.spacingNormal

                RowLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        text: "📋"
                        font.pixelSize: Styles.Theme.fontSizeMedium
                    }

                    Text {
                        text: qsTr("任务预览")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeMedium
                        font.weight: Styles.Theme.fontWeightMedium
                    }
                }

                Rectangle {
                    Layout.fillWidth: true
                    height: 1
                    color: Styles.Theme.divider
                }

                // 预览内容
                ColumnLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall
                    visible: selectedTemplate !== ""

                    RowLayout {
                        Layout.fillWidth: true
                        spacing: Styles.Theme.spacingSmall

                        Text {
                            text: qsTr("模板:")
                            color: Styles.Theme.textTertiary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            Layout.preferredWidth: 80
                        }

                        Text {
                            text: selectedTemplate
                            color: Styles.Theme.primary
                            font.pixelSize: Styles.Theme.fontSizeNormal
                            font.weight: Styles.Theme.fontWeightMedium
                            Layout.fillWidth: true
                        }
                    }

                    RowLayout {
                        Layout.fillWidth: true
                        spacing: Styles.Theme.spacingSmall

                        Text {
                            text: qsTr("执行AGV:")
                            color: Styles.Theme.textTertiary
                            font.pixelSize: Styles.Theme.fontSizeSmall
                            Layout.preferredWidth: 80
                        }

                        Text {
                            text: createTaskDialog.isAutoAgvSelection(selectedAgvId)
                                ? qsTr("系统自动分配")
                                : agvCombo.currentText
                            color: createTaskDialog.isAutoAgvSelection(selectedAgvId)
                                ? Styles.Theme.accent
                                : Styles.Theme.info
                            font.pixelSize: Styles.Theme.fontSizeNormal
                            font.weight: Styles.Theme.fontWeightMedium
                            Layout.fillWidth: true
                        }
                    }
                }

                // 无选择提示
                Text {
                    visible: selectedTemplate === ""
                    text: qsTr("请选择任务模板以查看预览")
                    color: Styles.Theme.textTertiary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                    font.italic: true
                    Layout.fillWidth: true
                    horizontalAlignment: Text.AlignHCenter
                }
            }
        }

        // 底部填充
        Item {
            Layout.fillHeight: true
        }
    }

    // 构建AGV列表模型
    function buildAgvModel() {
        var model = [
            { text: "🤖 " + qsTr("自动选择"), value: "" }
        ]

        var candidates = collectAvailableAgvs()
        var idleEntries = []

        for (var i = 0; i < candidates.length; ++i) {
            var agv = candidates[i]
            if (!isAgvIdle(agv)) {
                continue
            }

            var agvNumber = extractAgvNumber(agv)
            if (agvNumber === null) {
                continue
            }

            idleEntries.push({
                text: formatAgvLabel(agv, agvNumber),
                value: agvNumber
            })
        }

        idleEntries.sort(function(a, b) {
            if (typeof a.value === "number" && typeof b.value === "number") {
                return a.value - b.value
            }
            return String(a.text).localeCompare(String(b.text))
        })

        return model.concat(idleEntries)
    }

    // 公开方法
    function resetForm() {
        templateCombo.currentIndex = -1
        selectedTemplate = ""
        selectedAgvId = ""
        rebuildAgvOptions()
    }

    function rebuildAgvOptions() {
        agvOptions = buildAgvModel()

        if (!agvCombo || agvOptions.length === 0) {
            if (agvCombo) {
                agvCombo.currentIndex = agvOptions.length > 0 ? 0 : -1
            }
            selectedAgvId = ""
            return
        }

        var desiredValue = isAutoAgvSelection(selectedAgvId) ? "" : selectedAgvId
        var indexToSelect = 0

        if (!isAutoAgvSelection(desiredValue)) {
            for (var i = 0; i < agvOptions.length; ++i) {
                if (agvOptions[i].value === desiredValue) {
                    indexToSelect = i
                    break
                }
            }
        }

        agvCombo.currentIndex = indexToSelect
        selectedAgvId = agvOptions[indexToSelect].value
    }

    function collectAvailableAgvs() {
        if (!availableAgvs) {
            return []
        }

        if (Array.isArray(availableAgvs)) {
            return availableAgvs.slice()
        }

        var items = []
        var count = 0

        if (availableAgvs.count !== undefined) {
            count = availableAgvs.count
        } else if (typeof availableAgvs.rowCount === "function") {
            count = availableAgvs.rowCount()
        } else if (availableAgvs.length !== undefined) {
            count = availableAgvs.length
        }

        for (var i = 0; i < count; ++i) {
            var agvData = null
            if (typeof availableAgvs.getAgvData === "function") {
                agvData = availableAgvs.getAgvData(i)
            } else if (typeof availableAgvs.get === "function") {
                agvData = availableAgvs.get(i)
            } else if (availableAgvs[i] !== undefined) {
                agvData = availableAgvs[i]
            }

            if (agvData) {
                items.push(agvData)
            }
        }

        return items
    }

    function extractAgvNumber(agv) {
        if (!agv) {
            return null
        }

        if (agv.agvNumber !== undefined && agv.agvNumber !== null) {
            return Number(agv.agvNumber)
        }

        if (agv.id !== undefined && agv.id !== null) {
            var idValue = Number(agv.id)
            return isNaN(idValue) ? agv.id : idValue
        }

        if (agv.number !== undefined && agv.number !== null) {
            return Number(agv.number)
        }

        return null
    }

    function isAgvIdle(agv) {
        if (!agv) {
            return false
        }

        if (toBool(agv.online, agv.isOnline) === false) {
            return false
        }

        if (toBool(agv.isCharging, agv.charging) === true) {
            return false
        }

        if (toBool(agv.isControlled, agv.isControlledByDispatcher) === true) {
            return false
        }

        var statusText = (agv.status || "").toString().toLowerCase()
        if (statusText === "offline" || statusText === "charging") {
            return false
        }
        if (statusText === "idle") {
            return true
        }

        var station = agv.currentStation || agv.location
        if (!station || station.length === 0) {
            return false
        }

        return true
    }

    function formatAgvLabel(agv, agvNumber) {
        var name = agv.name || ("AGV" + padAgvNumber(agvNumber))
        var station = agv.currentStation || agv.location || qsTr("未知站点")
        var floorText = formatFloorText(agv.currentMap)
        var battery = extractBatteryLevel(agv)
        var batteryText = battery === null ? qsTr("未知电量") : qsTr("%1% 电量").arg(battery)
        return name + " · " + qsTr("空闲") + " / " + station + " / " + floorText + " / " + batteryText
    }

    function formatFloorText(mapName) {
        var unknownText = qsTr("未知楼层")

        if (!mapName || typeof GlobalMapViewModel === "undefined" || !GlobalMapViewModel) {
            return unknownText
        }

        var floor = GlobalMapViewModel.getFloorForMap(mapName)
        if (floor === null || floor === undefined || floor < 0) {
            return unknownText
        }
        return qsTr("第%1层").arg(floor)
    }

    function extractBatteryLevel(agv) {
        var battery = agv.batteryLevel !== undefined ? agv.batteryLevel : agv.battery
        battery = battery !== undefined ? battery : agv.power

        if (battery === undefined || battery === null) {
            return null
        }

        var numeric = Number(battery)
        if (isNaN(numeric)) {
            return null
        }

        numeric = Math.max(0, Math.min(100, Math.round(numeric)))
        return numeric
    }

    function padAgvNumber(value) {
        var number = Number(value)
        if (isNaN(number)) {
            return value
        }

        var text = number.toString()
        while (text.length < 3) {
            text = "0" + text
        }
        return text
    }

    function toBool() {
        for (var i = 0; i < arguments.length; ++i) {
            var value = arguments[i]
            if (value === undefined || value === null) {
                continue
            }

            if (typeof value === "boolean") {
                return value
            }

            if (typeof value === "number") {
                return value !== 0
            }

            if (typeof value === "string") {
                var normalized = value.toLowerCase()
                if (normalized === "true" || normalized === "1") {
                    return true
                }
                if (normalized === "false" || normalized === "0") {
                    return false
                }
            }
        }

        return undefined
    }

    function isAutoAgvSelection(value) {
        return value === "" || value === null || value === undefined
    }

    // 打开时重置
    onOpened: {
        resetForm()
        templateCombo.forceActiveFocus()
    }

    onAvailableAgvsChanged: rebuildAgvOptions()

    Connections {
        id: agvModelConnections
        ignoreUnknownSignals: true
        target: (typeof availableAgvs === "object"
                 && availableAgvs !== null
                 && typeof availableAgvs.rowCount === "function")
                 ? availableAgvs : null

        function onRowsInserted() { rebuildAgvOptions() }
        function onRowsRemoved() { rebuildAgvOptions() }
        function onModelReset() { rebuildAgvOptions() }
        function onDataChanged() { rebuildAgvOptions() }
        function onCountChanged() { rebuildAgvOptions() }
    }
}
